package com.fruit.auth.web.action;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.fruit.auth.model.Privilege;
import com.fruit.auth.model.Role;
import com.fruit.auth.service.PrivilegeService;
import com.fruit.auth.service.RoleService;
import com.fruit.system.model.Pager;
import com.fruit.system.model.Tree;
import com.fruit.web.action.util.BaseAction;

@Controller
@Scope("prototype")
public class RoleAction extends BaseAction<Role>
{
	
	private static final long serialVersionUID = -2098243530721402954L;
	
	@Resource(name="roleService")
	private RoleService roleService;
	
	@Resource(name="privilegeService")
	private PrivilegeService privilegeService;
	private Role role;
	
	private String privilegeIds;
	
	private String roleIds;
	public void setPrivilegeIds(String privilegeIds)
	{
		this.privilegeIds = privilegeIds;
	}
	
	public void setRoleIds(String roleIds)
	{
		this.roleIds = roleIds;
	}

	@Override
	public void prepare() throws Exception
	{
		role=new Role();
	}
	@Override
	public Role getModel()
	{
		return role;
	}

	public String roles()
	{
		Pager<Role> roles=roleService.findAllEntityByPager();
		renderJson(roles);
		return NONE;
	}
	
	public String update()
	{
		roleService.saveOrUpdateEntity(role);
		return NONE;
	}
	public String delete()
	{
		roleService.deleteRole(role);
		ajaxMsg.setSuccess(true);
		renderJson(ajaxMsg);
		return NONE;
	}
	
	public String deleteRoles()
	{
		roleService.deleteRoles(roleIds);
		ajaxMsg.setSuccess(true);
		renderJson(ajaxMsg);
		return NONE;
	}
	
	public String privileges()
	{
		List<Serializable> authPrivilegeIds=roleService.findRolePrivilegeIds(role);
		List<Privilege> allPrivileges=privilegeService.findAllPrivileges();
		final List<Tree> treeJSON=new ArrayList<Tree>();
		Tree tree=null;
		for(Privilege privilege:allPrivileges)
		{
				if(privilege.getPrivilegeEnabled())
				{
					tree=new Tree();
					tree.setId(privilege.getId());
					tree.setName(privilege.getName());
					tree.setPid(privilege.getParent()==null?null:privilege.getParent().getId());
					if(authPrivilegeIds.contains(privilege.getId()))
					{
						tree.setChecked(true);
					}
					treeJSON.add(tree);
				}
		}
		ajaxMsg.setSuccess(true);
		ajaxMsg.setData(treeJSON);
		renderJson(ajaxMsg);
		return NONE;
	}
	
	public String authPrivileges()
	{
		List<Serializable> ids=new ArrayList<Serializable>();
		if(!privilegeIds.equals(""))
		{
			String[] _ids=privilegeIds.split(",");
			for(String _id:_ids)
			{
				ids.add(Integer.parseInt(_id));
			}
		}
		
		roleService.updateRolePrivileges(role, ids);
		ajaxMsg.setSuccess(true);
		renderJson(ajaxMsg);
		return NONE;
	}
}
